package com.luedinski.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.luedinski.objects.Net;
import com.luedinski.objects.Trip;
import com.luedinski.utilities.HtmlUtilities;

/**
 * Gibt die Suchergebnisse der Verbindungen aus.
 * @author lueder
 *
 */
@WebServlet("/Routes")
public class RouteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Trip trip;
	private Net net;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RouteServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(false);

		if (session == null) {
			response.sendRedirect(response
					.encodeRedirectURL("/LuedinskiWays/Start"));
		}

		if (session.getAttribute("net") == null) {
			net = new Net();
			session.setAttribute("net", net);
		} else {
			net = (Net) session.getAttribute("net");
		}

		if (session.getAttribute("trip") == null) {
			trip = new Trip();
			session.setAttribute("trip", trip);
			response.sendRedirect(response
					.encodeRedirectURL("/LuedinskiWays/Start"));
		} else if (!((Trip) session.getAttribute("trip"))
				.isValidUserInputData()) {
			response.sendRedirect(response
					.encodeRedirectURL("/LuedinskiWays/Start"));
		} else {
			trip = (Trip) session.getAttribute("trip");

		}

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		out.println(HtmlUtilities.getHeader());
		if (trip != null && trip.isValidUserInputData()) {
			trip.generateTrips(net);
			//trip.checkConsistencyOfFinalTrips();
			out.println(trip.printTrips());
			out.println("<br /><h2>Your trips</h2>");
			out.println(trip.finalTripsToHtml());
		}
		else{
			out.println("No routes found!");
		}
		out.println("<br />");
		out.println(HtmlUtilities.getfooter());
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
